package yl.hs.bmipfull.service.production.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yl.hs.bmipfull.daos.production.IViolationReportDao;
import yl.hs.bmipfull.pojo.production.ProductShipOrderEntity;
import yl.hs.bmipfull.pojo.production.ViolationReportEntity;
import yl.hs.bmipfull.service.production.IViolationReportService;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.utils.SearchFilterEngine;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;
import yl.hs.bmipfull.viewmodels.SubmitModel;

import java.util.Date;
import java.util.Map;

/*
 * ViolationReportServiceImpl
 * @category
 * @author 谢景广
 * @date 2023-03-23
 */
@Service
public class ViolationReportServiceImpl extends ProductionBaseService implements IViolationReportService {

    @Override
    public PageResult<ViolationReportEntity> queryPage(PageQuery query, Integer rowNum, Integer page) {
        query.checkSortSides(ViolationReportEntity.class);
        query.getQuery().put("querySkip", (page - 1) * rowNum);
        query.getQuery().put("pageSize", rowNum);
        PageResult<ViolationReportEntity> result = new PageResult<>(rowNum);
        var filters = SearchFilterEngine.generateQueryList(query.getFilters(), ViolationReportEntity.class);
        result.setRecords(dao.queryRecords(query.getQuery(), filters));
        result.setPage(page);
        result.setData(dao.queryPage(query.getQuery(), filters));
        return result;
    }

    @Override
    public Integer save(SubmitModel model) throws Exception {
        ViolationReportEntity entity;
        Integer result;
        if(!Tl.isEmpty(model.getSn())){
            entity = dao.findBySN(model.getSn());
            var backJson = entity.toJson();
            var changeLog = Tl.getChangeLog(entity,model.getData());
            result = dao.update(entity);
            if(result>0){
                writeLog(ActionType.UPDATE,entity.getSn(),changeLog,backJson,entity.getClass());
            }
        }
        else {
            entity = new ViolationReportEntity();
            var user = HsApp.getCurrent();
            Tl.getChangeLog(entity,model.getData());
            entity.setSn(queryNewSN(entity.getClass()));
            entity.setAddTime(new Date());
            if(user!=null) {
                entity.setReportUserSN(user.getUserSN());
                entity.setReportUserName(user.getUserName());
            }
            result = dao.insertNew(entity);
            if(result>0){
                writeLog(ActionType.CREATE,entity.getSn(),"上报信息","",entity.getClass());
            }
        }
        return result;
    }

    @Autowired
    public void setDao(IViolationReportDao dao) {
        this.dao = dao;
    }

    private IViolationReportDao dao;
}
